package com.hmjk.health.views;

import com.hmjk.health.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.util.AttributeSet;
import android.view.View;

public class BatteryView extends View{
	private Context mContext;
	private int bat_percent = 100;
	private Drawable bg;
	private ShapeDrawable power;
	private int fullcolor;
	private int midcolor;
	private int lowcolor;
	
	public BatteryView(Context context) {
		super(context);
		mContext = context;
		init();
	}
	
	public BatteryView(Context context, AttributeSet attrs) {
		super(context, attrs, android.R.attr.textViewStyle);
		mContext = context;
		init();
	}
	
	public BatteryView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		init();
	}

	private void init(){
		fullcolor = mContext.getResources().getColor(R.color.BAT_FULL);
		midcolor = mContext.getResources().getColor(R.color.BAT_MID);
		lowcolor = mContext.getResources().getColor(R.color.BAT_LOW);
		bg = mContext.getResources().getDrawable(R.drawable.battery_view_bg);
		power = new ShapeDrawable(new RectShape());
		
		updateBackground(false);
	}
	
	private void updateBackground(boolean redraw){
		if(bat_percent == 100){
			power.getPaint().setColor(fullcolor);
		}else if(bat_percent > 50){
			power.getPaint().setColor(fullcolor);
		}else if(bat_percent > 20){
			power.getPaint().setColor(midcolor);
		}else{
			power.getPaint().setColor(lowcolor);
		}
	}
	
	public void setBatteryPercent(int per){
		bat_percent = per;
		if(bat_percent > 100){
			bat_percent = 100;
		}
		updateBackground(true);
	}
	
	private void drawBg(Canvas canvas) {   
        int h = getHeight();   
        int w = getWidth();  
        
        bg.setBounds(0, 0, w, h);   
        bg.draw(canvas);   
    }   
	
	private void drawPower(Canvas canvas){
		int h = getHeight();   
        int w = getWidth();  
        float density = getResources().getDisplayMetrics().density;
        int pad = (int) (1 * density);
        
        w = w - pad - pad;
        w = w * bat_percent / 100;
        
        power.setBounds(pad,pad,w+pad,h-pad);
        power.draw(canvas);  
        
	}
	
	@Override
	public void onDraw(Canvas canvas){
		super.onDraw(canvas);
		drawBg(canvas);
		drawPower(canvas);
	}
}
